<template>
	<el-dialog
		title="calculating"
		width="60%"
		:visible.sync="dialogVisible"
		@open="dialogOpen"
	>
		<div style="margin-bottom: 10px;font-size: 18px">
			{{ startTime }} - {{ endTime }}
		</div>
		<el-table
			:data="tableData"
			border
			:id="tableID"
		>
			<el-table-column label="name" prop="name"></el-table-column>
			<el-table-column label="MIN" prop="min"></el-table-column>
			<el-table-column label="MAX" prop="max"></el-table-column>
			<el-table-column label="AVE" prop="avg"></el-table-column>
		</el-table>
		<div slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false">Cancel</el-button>
			<el-button
				ref="copy"
				type="primary"
				class="btn"
				data-clipboard-action="copy"
				:data-clipboard-target="`#${tableID}`"
			>COPY</el-button>
		</div>
	</el-dialog>
</template>

<script>
import _ from "lodash"
import moment from 'moment'
import Clipboard from "clipboard"
import {v4 as uuidv4} from "uuid"

export default {
	name: 'CalculatingDialog',
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		zoomStart: {
			type: Number,
			default: 0
		},
		zoomEnd: {
			type: Number,
			default: 100
		},
		data: {
			type: Array,
			default: () => []
		},
		column: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			header: [],
			tableData: [],
			startTime: null,
			endTime: null,
			tableID: null,
			buttonId: null
		}
	},
	computed: {
		dialogVisible: {
			get() {
				return this.visible;
			},
			set(val) {
				val === false && this.resetData();
				this.$emit("update:visible", val);
			}
		}
	},
	mounted() {
		const clipboard = new Clipboard(`.btn`)
	},
	created() {
		this.tableID = `table-${uuidv4()}`
	},
	methods: {
		resetData() {},
		dialogOpen() {
			const startIndex = this.zoomStart !== 0 ? Math.floor(this.data.length * ( this.zoomStart / 100)) : 0
			const endIndex = this.zoomEnd !== 100 ? Math.floor(this.data.length * ( this.zoomEnd / 100)) : this.data.length
			const arr = this.data.slice(startIndex, endIndex)
			this.startTime = moment(parseInt(arr[0].data)).utcOffset(8).format("HH:mm:ss")
			this.endTime = moment(parseInt(arr[arr.length - 1].data)).utcOffset(8).format("HH:mm:ss")
			const tableMap = {}
			this.column.forEach(v => {
				const data = arr.filter(d => d[v.key] !== "").map(d => parseFloat(d[v.key]))
				tableMap[v.key] = {
					max: _.max(data),
					min: _.min(data),
					avg: _.floor(_.mean(data), 3)
				}
			})
			this.tableData = this.column.map(v => ({
				name: v.keyname,
				...tableMap[v.key]
			}))
		}
	}
}
</script>

<style scoped lang="scss">
::v-deep{
	.el-table th.el-table__cell{
		user-select: initial;
	}
}
</style>
